<?php
/**
 * SlugBehavior
 *
 * Saves pretty url's from titles to be used as unique identifier's
 * 
 * @author Chris de Kok <chris.de.kok@gmail.com>
 * @copyright Copyright (c) 2009 Chris de Kok. (http://mech7.net)
 *
 */
class SlugBehavior extends CActiveRecordBehavior {

    /**
    * The column name for the unqiue url
    */
    public $slug_col = 'slug';

    /**
    * The column name for the unqiue url
    */
    public $title_col = 'title';

	/**
	 * Primary key column name needs to be an id
	 * @var string
	 */
	public $pk_col;
	
    /**
     * Character to replace spaces
     * @var string
     */
    public $replace_space = '-';

    /**
     * Overwrite slug when updating
     */
     public $overwrite = true;

    /**
     * Before saving to database
     */
    public function beforeSave() {

		$this->pk_col = $this->Owner->getMetaData()->tableSchema->primaryKey;

                
        $slug = $this->getSlug($this->Owner->{$this->title_col});
        $this->Owner->{$this->slug_col} = $slug;

        $matches = $this->getMatches($this->Owner->slug);

        if($matches){
			$ar_matches = array();
			foreach ($matches as $match){
				if($match->{$this->pk_col} == $this->Owner->{$this->pk_col} && $match->{$this->slug_col} == $this->Owner->{$this->slug_col}){
				} else {
					$ar_matches[] = $match->slug;
				}
			}

			$new_slug = $slug;
			$index = 1;
			while ($index > 0) {
				if (in_array($new_slug, $ar_matches)){
					$new_slug = $slug.$this->replace_space.$index;
					$index++;
				} else {
					$slug = $new_slug;
					$index = -1;
				}
			}
		}
	
        if($this->Owner->isNewRecord){
            $this->Owner->{$this->slug_col} = $slug;
        }
        elseif ($this->overwrite === true) {
            $this->Owner->{$this->slug_col} = $slug;
        }
	return true;
    }

    /**
     * Lookup if string already exists in database
     * @param string $title 
     */
    public function getMatches($slug){
        $slugs = $this->Owner->findAll(array(
            'select'=> $this->slug_col.' , '.$this->title_col.' , '.$this->pk_col,
            'condition'=> $this->slug_col." LIKE '".$slug."%'"
        ));
        return $slugs;
    }

    /**
     * Convert string to slug 
     * @param string $title
     * @return mixed $slug
     */
    public function getSlug($title)
    {
               $title = trim($title);
              $title = preg_replace('/[\"\']+/','',$title);

		$pattern = "([[:punct:]])+";
		$string = ereg_replace($pattern, '', strtolower(htmlspecialchars(strtr(iconv("UTF-8", "ISO-8859-2", $title),  iconv("UTF-8", "ISO-8859-2", "ęóąśłżźćńĘÓĄŚŁŻŹĆŃ"), iconv("UTF-8", "ISO-8859-2", "eoaslzzcnEOASLZZCN")))));
		//$string = ereg_replace($pattern, '', strtolower(htmlspecialchars(strtr($title,  "ęóąśłżźćńĘÓĄŚŁŻŹĆŃ", "eoaslzzcnEOASLZZCN"))));
		//$string = iconv("UTF-8", "ISO-8859-1", $string);
		$pattern = "([[:space:]]|[[:blank:]])+";
                $slug = implode("-", array_slice (explode("-", ereg_replace($pattern, '-', $string)), 0, 5));
		return $slug;
    	/*
    	 * OLD
    	 */
    	//$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $title);
		//$clean = preg_replace("/[^a-zA-Z0-9\/_| -]/", '', $clean);
		//$clean = strtolower(trim($clean));
		//$clean = preg_replace("/[\/_| -]+/", $this->replace_space, $clean);

		//return $clean;
    }
}